/**
 * 处理数据库数据的操作
 */
const models = require('../models/init-models')
class BookService {
  // 创建书本
  async createBook(title, author, publication_date, genre, status) {
    // 写入数据库 
    const res = await models.lib_books.create({
      // 表的字段
      title,
      author,
      publication_date,
      genre,
      status
    })
    return res
    // return '操作成功'
  }

  // 删除书本
  async delBook(book_id) {
    const res = await models.lib_books.destroy({ where: { book_id } })
    return res
  }

  // 更新书本信息
  async updateBook(book_id, title, author, publication_date, genre, status) {
    try {
      let updateObj = {};
      if (title) updateObj.title = title;
      if (author) updateObj.author = author;
      if (publication_date) updateObj.publication_date = publication_date;
      if (genre) updateObj.genre = genre;
      if (status) updateObj.status = status;
      const res = await models.lib_books.update(updateObj, {
        where: { book_id }
      });
      return res;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  // 模糊查询书本（不传参数就是获取全部）
  async getBookInfo({ book_id, title, author, publication_date, genre, status }) {
    const whereOpt = {}
    book_id && Object.assign(whereOpt, { book_id })
    title && Object.assign(whereOpt, { title })
    author && Object.assign(whereOpt, { author })
    publication_date && Object.assign(whereOpt, { publication_date })
    genre && Object.assign(whereOpt, { genre })
    status && Object.assign(whereOpt, { status })

    const res = await models.lib_books.findAll({
      attributes: ['book_id', 'title', 'author', 'publication_date', 'genre', 'status'],
      where: whereOpt
    })
    return res ? res : null
  }

}

module.exports = new BookService()
